<template>
  <div class="Learning-useEventListener">
    <h3>使用 <code>useEventListener</code> 监听鼠标移动事件</h3>
    <codeContainer>
      <template #default>
        <p> 鼠标位置 at: {{ x }}px {{ y }}px</p>
        <div class="flex v h py-2">
          改变target 和 options 的值 会重新生成侦听器
          <button @click="changeTarget">changeTarget()</button>
          <button @click="changeOptions">changeOptions()</button>
        </div>
        <div class="flex v h py-2">
          调用useEventListener 返回的stop方法停止监听
          <button @click="stop">stop()</button>
        </div>
      </template>
      <template #code>
            <pre data-type="js">
              {{ codeFragment["vueUse-useEventListener-1"] }}
            </pre>
      </template>
    </codeContainer>
    <h3>使用 <code>useEventListener</code> 同时监听移入移出事件</h3>
    <codeContainer>
      <template #default>
        <div class="targetWrapper square-container bg" ref="targetWrapper"></div>
        <div class="flex v h py-2">
          调用useEventListener 返回的stop方法停止监听
          <button @click="targetWrapperStop">targetWrapperStop()</button>
        </div>
      </template>
      <template #code>
            <pre data-type="js">
              {{ codeFragment["vueUse-useEventListener-3"] }}
            </pre>
      </template>
    </codeContainer>
    <h3>实现 <code>useEventListener</code></h3>
    <ul class="Learning-summary">
      <li>1、target可以是ref 可以是组件实例 可以是dom对象</li>
      <li>2、可同时监听多个事件 ?? (根据vueuse源码的写法会交叉添加事件)</li>
      <li>3、修改target或options参数时会 注销再重新注册侦听</li>
      <li>4、可手动注销 或者 组件组件卸载时自动注销</li>
    </ul>
    <div class="code-source-wrapper" v-highlight>
      <pre data-type="js">
        {{ codeFragment["vueUse-useEventListener-2"] }}
      </pre>
    </div>
  </div>
</template>

<script setup>
import CodeContainer from '@/components/codeContainer/codeContainer.vue';
import { useEventListener } from '@/assets/js/hooks';
import {
  ref
} from 'vue';
import codeFragment from '../../assets/js/codeFragment';
// codeFragment-split
const x = ref(0);
const y = ref(0);
const options = ref({
  passive: true
});
const target = ref(window);

function changeOptions() {
  options.value = {
    passive: !options.value.passive
  };
}

function changeTarget() {
  target.value = target.value === window ? document : window;
}

function update(event) {
  x.value = event.pageX;
  y.value = event.pageY;
}
const stop = useEventListener(target, 'mousemove', update, options);
// codeFragment-split
const targetWrapper = ref(null);

function handleMouseover(e) {
  console.log('handleMouseover', e);
}

function handleMouseout(e) {
  console.log('handleMouseout', e);
}

// 会交叉调用  mouseover会注册两个listener ??
const targetWrapperStop = useEventListener(
  targetWrapper,
  [ 'mouseover', 'mouseout' ],
  [ handleMouseover, handleMouseout ],
  options
);
</script>
